/*!
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *
 *    Author: flareguner
 *    E-Mail: flareguner@gmail.com
 *    Years: 2010-2010
 */

#include "pronounce.h"

#include <QtCore/QString>
#include<QtCore/QDir>
#include <QtCore/QProcess>
#include <QtCore/QEventLoop>
#include <QtCore/QDebug>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkRequest>
#include <QtNetwork/QNetworkReply>

Pronounce::Pronounce(QObject *parent) :
    QObject(parent),
    m_process(new QProcess(this))
{
    connect(m_process, SIGNAL(finished(int)),this,SLOT(whenProcessFinished(int)));
}

Pronounce::~Pronounce() {
    stop();
}


void Pronounce::say(const QString &lang, const QString &text){
    if(isRunning()) {
        stop();
    }

    QUrl url("http://translate.google.com/translate_tts");
    QList<QPair<QString, QString> > query;
    query << QPair<QString, QString>("tl", lang);
    query << QPair<QString, QString>("q", text);
    url.setQueryItems(query);

    QNetworkAccessManager manager;
    QEventLoop loop;

    connect(&manager, SIGNAL(finished(QNetworkReply*)), &loop, SLOT(quit()));

    QNetworkRequest req(url);
    req.setRawHeader("User-Agent", "Mozilla/5.0");
    QNetworkReply *reply  = manager.get(req);
    loop.exec();

    qsrand(time(NULL));
    const int rand_value = qrand();
    m_file_path = QString("%1%2%3").
            arg(QDir::tempPath(), QDir::separator(), QString::number(rand_value) + "tts.mp3");


    const QByteArray mp3file = reply->readAll();
    QFile file(m_file_path);
    if(file.open(QFile::ReadWrite | QFile::Truncate)
            && ! mp3file.isEmpty()){
        file.write(mp3file);
        file.close();
    } else {
        return;
    }

    qDebug() << m_cmd + ' ' + m_file_path;
    m_process->start(m_cmd + ' ' + m_file_path);
}

bool Pronounce::isRunning() {
    if(m_process->state() == QProcess::Starting ||
            m_process->state() == QProcess::Running)
        return true;
    else
        return false;
}

void Pronounce::stop() {
    //! HACK: warning, this code may be dangerous!
    m_process->kill();
    m_process->waitForFinished(-1);
    QFile file(m_file_path);

    if(file.exists()) file.remove();
}

void Pronounce::whenProcessFinished(int i) {
    Q_UNUSED(i)
    QFile file (m_file_path);
    if(!file.remove())
       qWarning() << "Error! Can't remove file: "
                  << file.fileName() << " " << file.errorString();
    m_file_path.clear();

    emit finished();
}
